/*
 * @lc app=leetcode.cn id=113 lang=cpp
 *
 * [113] 路径总和 II
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    int targetSum = 0;           // 保存目标和
    int sum = 0;                 // 保存当前的和
    vector<int> path;            // 保存当前路径
    vector<vector<int>> result;  // 保存最终的结果

    vector<vector<int>> pathSum(TreeNode *root, int targetSum) {
        this->targetSum = targetSum;
        dfs(root);
        return result;
    }

    void dfs(TreeNode *root) {
        // 递归终止条件：空节点
        if (root == nullptr) return;

        // 递归终止条件：叶节点且 sum == targetSum
        if (root->left == nullptr && root->right == nullptr &&
            sum + root->val == targetSum) {
            path.push_back(root->val);
            result.push_back(path);
            path.pop_back();
            return;
        }

        // 类前序遍历，加入根节点
        path.push_back(root->val);
        sum += root->val;

        dfs(root->left);
        dfs(root->right);

        // 回溯，推出根节点
        path.pop_back();
        sum -= root->val;

        return;
    }
};
// @lc code=end
